<template>
  <n-text class="n-h4 text-gray-400" depth="3">修改密码</n-text>
  <n-form class="mt-4" ref="editPwdFormRef" :model="accountState.editPasswordForm" :rules="accountState.passwordRules">
    <n-form-item label="旧密码" path="password">
      <n-input v-model:value="accountState.editPasswordForm.password" size="large" placeholder="请输入旧密码" />
    </n-form-item>
    <n-form-item label="新密码" path="newPassword">
      <n-input v-model:value="accountState.editPasswordForm.newPassword" size="large" placeholder="请输入新密码" />
    </n-form-item>
    <n-space justify="end">
      <n-button type="primary" size="large" @click="submitEditPassword" :loading="accountState.changing">修改</n-button>
    </n-space>
  </n-form>
</template>

<script setup>
import { reactive, getCurrentInstance } from 'vue'
import { useUserStore } from '@/store'
import { changePass } from '@api/userApi'

const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const accountState = reactive({
  showPersonalDrawer: false,
  changing: false,
  editPasswordForm: {
    password: '',
    newPassword: ''
  },
  passwordRules: {
    password: { required: true, message: '请输入旧密码', trigger: 'input' },
    newPassword: {
      required: true,
      validator(rule, value) {
        if (!value) return new Error('请输入新密码')
        if (value.length < 6 || value.length > 18) return new Error('密码长度必须在6至18位')
        return true
      },
      trigger: 'input',
    }
  }
})

const submitEditPassword = async () => {
  proxy.$refs.editPwdFormRef.validate(async validate => {
    if (validate) return false
    try {
      accountState.changing = true
      const res = await changePass(accountState.editPasswordForm)
      if (res.statusCode !== 200) {
        accountState.changing = false
        return false
      }
      $message.success(res.message + '，正在退出登录。。。')
      setTimeout(() => {
        userStore.logout()
      }, 1000)
    } catch {
      accountState.changing = false
    }
  })
}
</script>

<style lang="less" scoped></style>